#include "pair_sampler_sorted.h"

void copy_pair_list(vector<pair<int, double> *> & ps, vector<pair<int, double> *> & psn, unsigned index) {
	for(unsigned i = 0; i < ps.size(); i++) {
		if(i != index) {
			psn.push_back(ps[i]);
		}
	}
}

int select_one_pair(vector<pair<int, double> *> & pair_list, double msum) {
	int l = pair_list.size();
	double sum = 0;
	double r = rand()/(double)RAND_MAX;
	r /= msum;
	int index = l - 1;
	for(int j = 0; j < l; j++) {
		sum += pair_list[j]->second;

		if(sum >= r) {
			index = j;
			break;
		}
	}
	return index;
}

void pair_sampler_sorted::select_indice(vector<pair<int, double> *> & pair_list, vector<int> & selected_list, int size) {
	for(int i = 0; i < size; i++) {
		int place = select_one_pair(pair_list, 1);
		int index = pair_list[place]->first;
		selected_list.push_back(index);
	}
}

void pair_sampler_sorted_once::select_indice(vector<pair<int, double> *> & pair_list, vector<int> & selected_list, int size) {
	if(size > (int)pair_list.size()) {
		size = (int)pair_list.size();
	}

	vector<pair<int, double> *> ps;
	copy_pair_list(pair_list, ps, -1);

	double msum = 1;
	for(int i = 0; i < size; i++) {
		int place = select_one_pair(ps, msum);
		pair<int, double> * p = ps[place];
		int index = p->first;
		selected_list.push_back(index);

		vector<pair<int, double> *> psn;
		copy_pair_list(ps, psn, place);
		ps = psn;
		msum -= p->second;
	}
}